/* eslint-disable max-len */
const { Service } = require('egg')
const cheerio = require('cheerio')
// eslint-disable-next-line import/no-extraneous-dependencies
const NodeRSA = require('node-rsa')
const crypto = require('crypto')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data

      /* * 0. 请求门户主页获取登入所需参数 */
      const indexUrl = 'https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421f3f652d12e7e605e6b1b9de29d51367b10e1/cas/login?service=https%3A%2F%2Fi.hnust.edu.cn%2F%3Fpath%3Dhttps%3A%2F%2Fi.hnust.edu.cn%2Fmain.html%23%2F'
      const indexRes = await ctx.curl(indexUrl, {
        method: 'GET',
        headers: {
          Host: 'webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
      })
      const setCookie = indexRes.headers['set-cookie'] ? indexRes.headers['set-cookie'].map((e) => e.split(';')[0])[0] : ''
      console.log('setCookie', setCookie)

      const $ = cheerio.load(indexRes.data.toString())
      const parameter = {}
      $('#fm1').find('input').each((i, e) => {
        const attrs = $(e).attr()
        parameter[attrs.name] = attrs.value || ''
      })
      delete parameter.rememberMe
      parameter.username = sid
      parameter.failN = '0'
      // parameter.fpVisitorId = '6e612db5b15c9e77500038c71825a854';  // 浏览器指纹
      parameter.fpVisitorId = crypto.randomBytes(Math.ceil(32 / 2)).toString('hex').slice(0, 32) // 随机生成32位字符
      console.log('fpVisitorId', parameter.fpVisitorId)

      /* 请求公钥 */
      const publicKeyUrl = 'https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421f3f652d12e7e605e6b1b9de29d51367b10e1/cas/jwt/publicKey?vpn-12-o2-cas-i.hnust.edu.cn'
      const publicKeyRes = await ctx.curl(publicKeyUrl, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
      })

      /* 密码加密 */
      const newkey = new NodeRSA(publicKeyRes.data.toString(), 'pkcs8-public')
      newkey.setOptions({ encryptionScheme: 'pkcs1' })// 因为jsencrypt自身使用的是pkcs1加密方案,后端加密时与其统一
      parameter.password = `__RSA__${newkey.encrypt(pwd, 'base64')}`

      /* * 1. 登录信息门户 */
      const loginUrl = 'https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421f3f652d12e7e605e6b1b9de29d51367b10e1/cas/login?service=https%3A%2F%2Fi.hnust.edu.cn%2F%3Fpath%3Dhttps%3A%2F%2Fi.hnust.edu.cn%2Fmain.html%23%2F'
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
        data: parameter,
      })
      // console.log('login', login_res.status, login_res.headers.location);
      if (loginRes.status === 401) return { status: 200 }
      /* end */

      const RedirectRes1 = await ctx.curl(loginRes.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes1', RedirectRes1.status, RedirectRes1.headers.location);

      const RedirectRes2 = await ctx.curl(RedirectRes1.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes2', RedirectRes2.status, RedirectRes2.headers.location);

      const RedirectRes3 = await ctx.curl(`https://webvpn.hnust.edu.cn${RedirectRes2.headers.location}`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes3', RedirectRes3.status, RedirectRes3.headers.location);

      const RedirectRes4 = await ctx.curl(RedirectRes3.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes4', RedirectRes4.status, RedirectRes4.headers.location);

      const RedirectRes5 = await ctx.curl(`https://webvpn.hnust.edu.cn${RedirectRes4.headers.location}`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes5', RedirectRes5.status, RedirectRes5.headers.location);

      const RedirectRes6 = await ctx.curl(`https://webvpn.hnust.edu.cn${RedirectRes5.headers.location}`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes6', RedirectRes6.status, RedirectRes6.headers.location);

      await ctx.curl(`https://webvpn.hnust.edu.cn${RedirectRes6.headers.location}`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('RedirectRes7', RedirectRes7.status);

      // const res = await ctx.curl('https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421f9b9499232237c1e7b0c9ce29b5b/portal-api/v2/theme/themeInfo', {
      //   method: 'GET',
      //   headers: {
      //     Cookie: setCookie,
      //     Host: 'webvpn.hnust.edu.cn',
      //     Origin: 'https://webvpn.hnust.edu.cn',
      //     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
      //   },
      // });
      // console.log('res', res.status, res.data.toString());

      /*  3.教务登录 */
      const EAres = await ctx.curl('https://webvpn.hnust.edu.cn/https/77726476706e69737468656265737421f3f652d12e7e605e6b1b9de29d51367b10e1/cas/login?service=https://kdjw.hnust.edu.cn/sso.jsp', {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('tem_res', EA_res.status, EA_res.headers.location);

      const EARedirectRes1 = await ctx.curl(EAres.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('EARedirectRes1', EARedirectRes1.status, EARedirectRes1.headers.location);

      const EARedirectRes2 = await ctx.curl(EARedirectRes1.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('EARedirectRes2', EARedirectRes2.status, EARedirectRes2.headers.location);

      await ctx.curl(EARedirectRes2.headers.location, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          Host: 'webvpn.hnust.edu.cn',
          Origin: 'https://webvpn.hnust.edu.cn',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
      })
      // console.log('EARedirectRes3', EARedirectRes3.status, EARedirectRes3.headers.location);

      return { setCookie, status: 302 }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
